<template>
  <div class="exercise-result">
    <h2 class="mb-4 text-2xl font-bold">
      {{ exercise.exercise.exerciseName }}
    </h2>
    <p class="mb-2 text-muted">
      总分：{{ exercise.exercise.exerciseScore }}分 | 题目数量：{{ exercise.questions.length }}道
    </p>

    <div class="mb-6">
      <p class="text-gray-600">
        <span 
          :class="{'text-green-600': exercise.studentExercise.studentScore >= exercise.exercise.exerciseScore * 0.6, 'text-red-600': exercise.studentExercise.studentScore < exercise.exercise.exerciseScore * 0.6}"
        >
          最终得分：{{ exercise.studentExercise.studentScore }}分 ({{ calculateScorePercentage() }}%)
        </span>
      </p>

      <div class="mt-3 h-1 bg-gray-200 rounded-full">
        <div 
          class="bg-blue-500 rounded-full h-full" 
          :style="{ width: `${(exercise.studentExercise.studentScore / exercise.exercise.exerciseScore) * 100}%` }"
        />
      </div>
    </div>

    <div class="space-y-6">
      <!-- 遍历题目（qwa = question with answer） -->
      <div
        v-for="(qwa, index) in exercise.questions"
        :key="qwa.question.questionId"
      >
        <div class="border-l-4 border-blue-500 pl-4 py-2">
          <h4 class="font-semibold text-lg">
            题目 {{ index + 1 }}: 
            <span v-html="parseLineBreaks(qwa.question.questionContent)" />
            <span class="ml-2 text-sm text-gray-500">({{ qwa.question.questionScore }}分)</span>
          </h4>
          <button 
            class="favorite-btn"
            :disabled="isQuestionFavorited(qwa.question.questionId)"
            @click="addToFavorite(qwa.question.questionId)"
          >
            {{ isQuestionFavorited(qwa.question.questionId) ? '已收藏' : '添加收藏' }}
          </button>


          <!-- 选择题（type: false 表示选择题） -->
          <div
            v-if="!qwa.question.type"
            class="mt-3"
          >
            <!-- 正确答案 -->
            <div class="mb-2 text-gray-600">
              <strong class="text-gray-700">正确答案：</strong>
              <span class="text-green-600">{{ formatOptions(qwa.question.questionAnswer) }}</span>
            </div>

            <!-- 学生答案 -->
            <div class="mb-2">
              <strong class="text-gray-700">你的答案：</strong>
              <span 
                :class="getAnswerStatusClass(qwa)"
              >
                {{ getStudentAnswerDisplay(qwa) }}
              </span>
            </div>

            <!-- 得分 -->
            <div class="mt-2 text-sm">
              <span class="text-gray-600">
                本题得分：{{ qwa.studentAnswer?.gainScore || 0 }} / {{ qwa.question.questionScore }}
              </span>
            </div>
          </div>

          <!-- 解答题（type: true 表示解答题） -->
          <div
            v-else
            class="mt-3"
          >
            <!-- 参考答案 -->
            <div class="mb-2 text-gray-600">
              <strong class="text-gray-700">参考答案：</strong>
              <p class="ml-2 text-gray-600">
                {{ qwa.question.questionAnswer || '无参考答案' }}
              </p>
            </div>

            <!-- 学生答案 -->
            <div class="mb-2">
              <strong class="text-gray-700">你的答案：</strong>
              <p class="ml-2 text-gray-800">
                {{ qwa.studentAnswer?.studentAnswer || '未作答' }}
              </p>
            </div>

            <!-- 得分 -->
            <div class="mt-2 text-sm">
              <span class="text-gray-600">
                本题得分：{{ qwa.studentAnswer?.gainScore || 0 }} / {{ qwa.question.questionScore }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <button
      class="btn btn-secondary mt-4"
      @click="$emit('back')"
    >
      <i class="fa fa-chevron-left me-1" /> 返回练习列表
    </button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  props: {
    exercise: {
      type: Object,
      required: true
    },
    userId: {
      type: String,
      required: true
    },
    courseId: {
      type: String,
      required: true
    },
  },
  data() {
    return {
      favoriteQuestionIds: [] // 存储用户已收藏的题目ID
    };
  },

  mounted() {
    this.fetchFavoriteQuestions(); // 组件挂载时加载收藏列表
  },

  methods: {
    async fetchFavoriteQuestions() {
      try {
        const response = await axios.get('/api/exercises/favorite', {
          params: {
            userId: this.userId,
            courseId: this.courseId
          }
        });

        if (response.data && Array.isArray(response.data)) {
          this.favoriteQuestionIds = response.data.map(q => q.questionId);
        } else {
          this.favoriteQuestionIds = [];
        }
      } catch (error) {
        console.error('获取收藏题目失败:', error);
        this.favoriteQuestionIds = [];
      }
    },

    isQuestionFavorited(questionId) {
      return this.favoriteQuestionIds.includes(questionId);
    },

    async addToFavorite(questionId) {
      const userId = this.userId;
      const courseId = this.courseId;

      if (!userId || !courseId || !questionId) {
        console.log('exercise 数据:', this.exercise);
        console.log(userId, courseId, questionId);
        console.error('参数缺失');
        alert('参数不完整，无法收藏');
        return;
      }
      if (this.isQuestionFavorited(questionId)) {
        alert('收藏失败：已经收藏了本题目');
        return;
      }

      try {
        await axios.post('/api/exercises/favorite', null, {
          params: {
            userId,
            courseId,
            questionId
          }
        });
        
      // ✅ 收藏成功后，把 questionId 加入数组
          this.favoriteQuestionIds.push(questionId);

        alert('收藏成功');
      } catch (error) {
        console.error('收藏失败:', error);
        alert('收藏失败，请重试');
      }
    },
    // 计算得分百分比
    calculateScorePercentage() {
      return this.exercise.exercise.exerciseScore > 0 
        ? Math.round((this.exercise.studentExercise.studentScore / this.exercise.exercise.exerciseScore) * 100) 
        : 0;
    },

    // 格式化选项（如"AC"转为"A. C. "）
    formatOptions(answer) {
      return answer ? answer.split('').map(letter => `${letter}. `).join('') : '';
    },

    // 解析换行符（将\n转为<br>）
    parseLineBreaks(text) {
      return text ? text.replace(/\n/g, '<br>') : '';
    },

    // 获取答案状态样式（正确/错误/未作答）
    getAnswerStatusClass(qwa) {
      const studentAnswer = qwa.studentAnswer?.studentAnswer || '';
      const correctAnswer = qwa.question.questionAnswer || '';
      
      if (!studentAnswer) return 'text-gray-500'; // 未作答
      return studentAnswer === correctAnswer ? 'text-green-600' : 'text-red-600';
    },

    // 获取学生答案显示文本（处理null情况）
    getStudentAnswerDisplay(qwa) {
      const studentAnswer = qwa.studentAnswer?.studentAnswer;
      if (!studentAnswer) return '未作答';
      return this.formatOptions(studentAnswer);
    }
  }
};
</script>

<style scoped>
.exercise-result {
  padding: 2rem;
  margin-top: 2rem;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

/* 答案状态颜色 */
.text-green-600 { color: #059669; }
.text-red-600 { color: #dc2626; }
.text-gray-500 { color: #6b7280; }
.favorite-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 6px 12px;
  margin-top: 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.875rem;
  transition: background-color 0.3s;
}

.favorite-btn:hover {
  background-color: #45a049;
}
</style>
